// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT

package utils

import (
	"fmt"
	"testing"
	"time"
)

func TestIsUnixSocket(t *testing.T) {
	tests := []struct {
		path     string
		expected bool
	}{
		{"/tmp/sock", true},
		{"./sock", true},
		{"localhost:8080", false},
		{"127.0.0.1:8080", false},
		{"sock", false},
	}

	for _, tt := range tests {
		result := IsUnixSocket(tt.path)
		if result != tt.expected {
			t.Errorf("IsUnixSocket(%q) = %v, want %v", tt.path, result, tt.expected)
		}
	}
}

func TestIsTCPAddress(t *testing.T) {
	tests := []struct {
		addr     string
		expected bool
	}{
		{"localhost:8080", true},
		{"127.0.0.1:8080", true},
		{"/tmp/sock", false},
		{"sock", false},
	}

	for _, tt := range tests {
		result := IsTCPAddress(tt.addr)
		if result != tt.expected {
			t.Errorf("IsTCPAddress(%q) = %v, want %v", tt.addr, result, tt.expected)
		}
	}
}

func TestParseSocketAddress(t *testing.T) {
	tests := []struct {
		addr         string
		expectedType string
		expectedAddr string
		expectError  bool
	}{
		{"/tmp/sock", "unix", "/tmp/sock", false},
		{"localhost:8080", "tcp", "localhost:8080", false},
		{"127.0.0.1:8080", "tcp", "127.0.0.1:8080", false},
		{"invalid", "", "", true},
	}

	for _, tt := range tests {
		socketType, addr, err := ParseSocketAddress(tt.addr)
		if tt.expectError && err == nil {
			t.Errorf("ParseSocketAddress(%q) should return error", tt.addr)
		}
		if !tt.expectError && err != nil {
			t.Errorf("ParseSocketAddress(%q) returned error: %v", tt.addr, err)
		}
		if !tt.expectError {
			if socketType != tt.expectedType {
				t.Errorf("ParseSocketAddress(%q) type = %v, want %v", tt.addr, socketType, tt.expectedType)
			}
			if addr != tt.expectedAddr {
				t.Errorf("ParseSocketAddress(%q) addr = %v, want %v", tt.addr, addr, tt.expectedAddr)
			}
		}
	}
}

func TestFormatDuration(t *testing.T) {
	tests := []struct {
		duration time.Duration
		expected string
	}{
		{100 * time.Millisecond, "100ms"},
		{1500 * time.Millisecond, "1.50s"},
		{2 * time.Minute, "2m0s"},
	}

	for _, tt := range tests {
		result := FormatDuration(tt.duration)
		if result != tt.expected {
			t.Errorf("FormatDuration(%v) = %q, want %q", tt.duration, result, tt.expected)
		}
	}
}

func TestRetry(t *testing.T) {
	attempts := 0
	err := Retry(3, 10*time.Millisecond, func() error {
		attempts++
		if attempts < 3 {
			return fmt.Errorf("temporary error")
		}
		return nil
	})

	if err != nil {
		t.Errorf("Retry should succeed, got error: %v", err)
	}
	if attempts != 3 {
		t.Errorf("Retry should attempt 3 times, got %d", attempts)
	}
}
